from flask import Blueprint, render_template, redirect,request
from AdminApiRunner.app import db, rpc
from AdminApiRunner.core.Utils import ReturnUtil, PasswdUtil, AuthUtil
from functools import wraps
from nameko.rpc import RpcProxy


from .models import User
user = Blueprint('user',__name__)

def apiauthorize(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        result = AuthUtil.identify(request)
        if result['status']:
            return func(*args, **kwargs)
        else:
            return ReturnUtil.Error(msg=result['msg'],data=result['data'])
    return wrapper

@user.route('/pvdata')
def pvdata():
    scada_service = RpcProxy('scada_service')
    # result = scada_service.send.async("scada_service_test")
    result = rpc.scada_service.get_histrydatas()
    return ReturnUtil.Success(msg="ok",data=result)

@user.route('/index')
def index():
    return render_template('user/index.html')

@user.route('/register', methods=["POST"])
def register():
    p_user = request.form.get('username', None)
    p_password = request.form.get('password', None)
    if not p_user:
        return ReturnUtil.Error(msg="请输入用户名")

    newobj = User(username=p_user, email="", password=PasswdUtil.md5(p_password))
    db.session.add(newobj)
    db.session.commit()
    return ReturnUtil.Success(data=newobj)

@user.route('/login',methods=['GET','POST'])
def login():
    p_user = request.form.get('username', None)
    p_password = request.form.get('password', None)
    if not p_user:
        return ReturnUtil.Error(msg="请输入用户名")
    if not p_password:
        return ReturnUtil.Error(msg="请输入密码")

    return AuthUtil.authenticate(p_user, p_password)



@user.route('/list',methods=['GET','POST'])
@apiauthorize
def list():
    users = User.query.all()
    return ReturnUtil.Success(data=users)

@user.route('/add',methods=['GET','POST'])
@apiauthorize
def add():
    p_user = request.form.get('username',None)
    p_email = request.form.get('email',None)
    p_password = request.form.get('password',None)

    if not p_user or not p_password:
        return ReturnUtil.Error(msg="输入参数非法")

    newobj = User(username=p_user, email=p_email, password=PasswdUtil.md5(p_password))
    db.session.add(newobj)
    db.session.commit()
    return ReturnUtil.Success(data=newobj)

